package student;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/StudentAvailableExamsServlet")
public class StudentAvailableExamsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer studentId = (Integer) session.getAttribute("student_id");
        Integer classId = (Integer) session.getAttribute("class_id");

        if (studentId == null || classId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        response.setContentType("application/json;charset=UTF-8");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root", "root", "com.mysql.cj.jdbc.Driver");

            if (conn.open()) {
                String sql = "SELECT e.exam_id, e.exam_name, c.course_name, e.start_time, e.duration, e.status " +
                        "FROM exam e " +
                        "JOIN course c ON e.course_id = c.course_id " +
                        "JOIN exam_class ec ON e.exam_id = ec.exam_id " +
                        "WHERE ec.class_id = ? AND e.status = 2 " +
                        "AND e.exam_id NOT IN ( " +
                        "   SELECT exam_id FROM student_score WHERE student_id = ? " +
                        ") " +
                        "ORDER BY e.start_time DESC"
                        ;

                ResultSet rs = conn.executeSql(sql, new Object[]{classId, studentId});
                List<Map<String, Object>> exams = new ArrayList<>();

                while (rs.next()) {
                    Map<String, Object> exam = new LinkedHashMap<>();
                    exam.put("exam_id", rs.getInt("exam_id"));
                    exam.put("exam_name", escapeJson(rs.getString("exam_name")));
                    exam.put("course_name", escapeJson(rs.getString("course_name")));

                    // 格式化时间
                    Timestamp startTime = rs.getTimestamp("start_time");
                    exam.put("start_time", startTime != null ?
                            escapeJson(sdf.format(startTime)) : "N/A");

                    exam.put("duration", rs.getInt("duration"));
                    exam.put("status", rs.getInt("status"));
                    exams.add(exam);
                }

                response.getWriter().print(mapListToJson(exams));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("{\"error\": \"加载考试列表失败: " + e.getMessage() + "\"}");
        }
    }

    private String mapListToJson(List<Map<String, Object>> list) {
        StringBuilder json = new StringBuilder("[");
        boolean firstItem = true;

        for (Map<String, Object> item : list) {
            if (!firstItem) {
                json.append(",");
            }
            firstItem = false;

            json.append("{");
            boolean firstEntry = true;

            for (Map.Entry<String, Object> entry : item.entrySet()) {
                if (!firstEntry) {
                    json.append(",");
                }
                firstEntry = false;

                json.append("\"")
                        .append(escapeJson(entry.getKey()))
                        .append("\":");

                Object value = entry.getValue();
                if (value == null) {
                    json.append("null");
                } else if (value instanceof String) {
                    json.append("\"")
                            .append(escapeJson((String) value))
                            .append("\"");
                } else {
                    json.append(value);
                }
            }

            json.append("}");
        }

        json.append("]");
        return json.toString();
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}